<template>
  <van-row v-if="!playing">
    <van-col :span="6">
      <add-comp @submit="addGame" v-if="!playing"></add-comp
    ></van-col>
    <van-col :span="18" style="text-align: right">
      <van-button type="primary" round="true" @click="$router.push('info')">
        <van-icon name="contact" />
        {{ userName }}</van-button
      >
      <van-button type="warning" round="true" @click="logout" v-show="!playing"
        >登出</van-button
      ></van-col
    >
  </van-row>
  <div v-show="playing">
    <play-comp
      :connection="connection"
      @exit="returnToGameList"
      ref="playcomp"
    ></play-comp>
  </div>
  <div v-if="!playing" style="padding: 2px">
    <van-row
      v-for="(game, index) in games"
      :key="game.id"
      @click="joinGame(game.id)"
      :class="index % 2 == 0 ? 'on' : 'off'"
    >
      <van-col span="1"></van-col>
      <van-col span="11"
        >{{ game.description
        }}<van-tag type="primary">{{ game.gameType }}</van-tag>
        <van-tag type="success">{{ game.playType }}</van-tag></van-col
      >
      <van-col span="11">{{ game.gameContext }}</van-col>
      <van-col span="1"></van-col>
    </van-row>
  </div>
  <van-notice-bar v-if="message" :scrollable="false" :text="message" />
</template>

<script>
import Oidc from "oidc-client";
import { HubConnectionBuilder } from "@microsoft/signalr";
import addComp from "@/components/CreateGame.vue";
import playComp from "@/components/PlayGame.vue";
import { usePlayStore } from "@/stores/playstore";

const config = {
  odicconfig: {
    authority: import.meta.env.VITE_AUTHORITY,
    client_id: import.meta.env.VITE_CLIENTID,
    redirect_uri: import.meta.env.VITE_REDIRECTURI,
    response_type: "code",
    scope: import.meta.env.VITE_SCOPE,
    post_logout_redirect_uri: import.meta.env.VITE_POSTLOGOUTREDIRECTURI,
  },
  signalRUrl: import.meta.env.VITE_SIGNALRURL,
};

export default {
  data() {
    return {
      connection: null,
      games: [],
      userName: "",
      mgr: null,
      playing: false,
      message: "消息",
      store: null,
    };
  },
  created() {
    this.store = usePlayStore();
    var mgr = new Oidc.UserManager(config.odicconfig);
    var me = this;
    me.mgr = mgr;
    mgr.getUser().then(function (user) {
      if (user) {
        me.store.user = user;
        me.userName = user.profile.name;
        me.connection = new HubConnectionBuilder()
          .withUrl(config.signalRUrl, {
            accessTokenFactory: () => user.access_token,
          })
          .withAutomaticReconnect()
          .build();
        me.connection.Error += (ex) => {
          console.WriteLine("Error: {0}", ex.Message);
          me.message = ex.Message;
        };
        me.connection.on("PlayerExist", function () {
          me.message = "获取游戏列表......";
          me.connection.invoke("GetGames", me.userName);
        });
        me.connection.on("PlayerNotExist", function (userName) {
          me.message = "创建玩家......";
          me.connection.invoke("AddPlayer", userName, userName);
        });

        me.connection.on("PlayerAdded", function () {
          me.message = "获取游戏列表......";
          me.connection.invoke("GetGames", me.userName);
        });
        me.connection.on("RefreshGames", function () {
          me.message = "获取游戏列表......";
          me.connection.invoke("GetGames", me.userName);
        });
        me.connection.on("ShowGames", function (games) {
          me.message = "数据获取完成";
          me.ShowGames(games);
        });
        me.connection.on("EnterGame", function (gameid) {
          me.playGame(gameid);
        });
        me.connection.on("Error", function (message) {
          me.message = message;
        });
        me.$refs.playcomp.init(me.connection);
        me.connection
          .start()
          .then(function () {
            me.message = "检查玩家是否存在......";
            me.connection
              .invoke("CheckUser", me.userName)
              .catch(function (err) {
                me.message = "发生错误：" + err.toString() + "，请重新登录。";
              });
          })
          .catch(function (err) {
            me.message = err.toString();
            //return console.error(err.toString());
          });
      } else {
        mgr.signinRedirect();
      }
    });
  },
  methods: {
    ShowGames: function (games) {
      this.message = "";
      this.games = games;
    },
    joinGame: function (id) {
      var me = this;
      this.connection
        .invoke("JoinGame", this.userName, id)
        .catch(function (err) {
          me.message = err.toString();
        });
    },
    addGame: function (game) {
      //console.log(game);
      var me = this;
      me.message = "添加新游戏.....";
      this.connection
        .invoke(
          "AddNewGame",
          this.userName,
          game.gameDesc,
          game.gameType,
          game.playtype,
          game.gameContext
        )
        .catch(function (err) {
          me.message = err.toString();
        });
    },
    playGame: function (id) {
      this.playing = true;
      this.$refs.playcomp.loadGame(this.userName, id);
      this.store.gameid = id;
    },
    logout: function () {
      this.mgr.signoutRedirect();
    },
    returnToGameList: function () {
      var me = this;
      this.playing = false;
      this.message = "获取游戏列表......";
      this.connection.invoke("GetGames", me.userName).catch(function (err) {
        me.message = err.toString();
      });
    },
  },
  components: {
    addComp,
    playComp,
  },
};
</script>

<style scoped>
.on {
  background: #eeeeee;
  padding-top: 15px;
  padding-bottom: 15px;
  font-size: 3.5mm;
}

.off {
  padding: 4px;
  font-size: 3.5mm;
  padding-top: 15px;
  padding-bottom: 15px;
  border-top: 1px solid #aaaaaa;
}
</style>
